package com.datastructure.test.dynamic.stringtoip;

import java.util.ArrayList;

public class StringTransformToIp {

    private StringBuilder stringBuilder;

    public static void main(String[] args) {
        String data = "010010";
//        System.out.println(data.substring(1,4));
        StringTransformToIp stringTransformToIp = new StringTransformToIp();
        ArrayList<String> strings = stringTransformToIp.restoreIpAddresses(data);
        System.out.println(strings);
    }

    public ArrayList<String> restoreIpAddresses (String s) {
        // write code here
        String s1;
        String s2;
        String s3;
        String s4;
        ArrayList<String> res = new ArrayList<>();
        if(s.length()==4){
            stringBuilder = new StringBuilder();
            stringBuilder.append(s.charAt(0));
            stringBuilder.append(".");
            stringBuilder.append(s.charAt(1));
            stringBuilder.append(".");
            stringBuilder.append(s.charAt(2));
            stringBuilder.append(".");
            stringBuilder.append(s.charAt(3));
            res.add(stringBuilder.toString());
            return res;
        }
        if(s.startsWith("00")){
            return res;
        }
        for (int i = 1; i < 4; i++) {
            for(int j = s.length()-1;j>s.length()-4;j--){
                if(j>=i+2) {
                    for (int k = i + 1; k < j; k++) {
                        s1 = s.substring(0, i);
                        s2 = s.substring(i, k);
                        s3 = s.substring(k, j);
                        s4 = s.substring(j, s.length());
                        if (isIp(s1) && isIp(s2) && isIp(s3) && isIp(s4)
                        && isStartWithZero(s1)
                                && isStartWithZero(s2)
                                && isStartWithZero(s3)
                                && isStartWithZero(s4)) {
                            stringBuilder = new StringBuilder();
                            stringBuilder.append(s1);
                            stringBuilder.append(".");
                            stringBuilder.append(s2);
                            stringBuilder.append(".");
                            stringBuilder.append(s3);
                            stringBuilder.append(".");
                            stringBuilder.append(s4);
                            res.add(stringBuilder.toString());
                        }
                    }
                }
            }
        }
        return res;
    }

    public boolean isIp(String ip){
        int data = Integer.parseInt(ip);
        return data >= 0 && data <= 255;
    }

    public boolean isStartWithZero(String ip){
        return !ip.startsWith("0") || ip.length() <= 1;
    }
}
